﻿using Lion.WeiXin.Core.Data;
using Lion.WeiXin.Core.Models;
using Lion.WeiXin.Tools.Log;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Lion.WeiXin.Controllers
{
    public class WeChatNewsController : Controller
    {
        DBContext db;

        public WeChatNewsController()
            : this(null)
        {

        }

        public WeChatNewsController(DBContext mockDB)
        {
            if (mockDB == null)
            {
                db = new DBContext();
            }
            else
            {
                db = mockDB;
            }
        }

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        ///  获取分页列表数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="msgType"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public string GetPageList(string name, int currentPage, int pageSize)
        {
            //如果传入条件参数
            name = HttpUtility.UrlDecode(name);
            List<NewsModel> list = new List<NewsModel>();
            int totalCount = 0;
            //string where = string.Format(" title like '%{0}%'", name);
            //if (!string.IsNullOrEmpty(name))
            //{
            //    list = db.News.GetList(pageSize, currentPage,where );
            //    totalCount = db.News.GetRecordCount(where);
            //}
            //else
            //{
            //    list = db.News.GetList(pageSize, currentPage, "");
            //    totalCount = db.News.GetRecordCount("");
            //}
            list = db.News.GetList(pageSize, currentPage, "");
            totalCount = db.News.GetRecordCount("");

            string jsonResult = JsonConvert.SerializeObject(list, new IsoDateTimeConverter());
            jsonResult = "{\"total\":" + totalCount + "," + "\"data\":" + jsonResult + "}";
            return jsonResult;
        }

        //图文消息群发步骤
        //1 上传单条文章图片，获取media_id （缩略图 thumb_media_id）

        //2 把所有文章组装成一个图文news 素材，上传到微信，返回图文news 媒体id（media_id，type=news）

        //3 调用群发post 接口
        //https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=ACCESS_TOKEN


        public ActionResult Show(int ID)
        {
            NewsModel model = db.News.GetModel(ID);
            //  InitTemplateType(model.TemplateID);
            // InitCategoryType(model.CategoryCode);
            return View(model);
        }

        public ActionResult Create()
        {
            //根据当前栏目，计算新栏目的code值
            NewsModel model = new NewsModel();
            return View(model);
        }

        //栏目，查询首页模板和栏目模板，栏目一级为首页模板
        private void InitTemplateType(int selectID)
        {
            //加载产品类型
            List<TemplateModel> dic_pro_types = db.Templates.GetList("TypeCode ='105003'");
            List<SelectListItem> selectTypes = new List<SelectListItem>();

            selectTypes.Add(new SelectListItem() { Value = "0", Text = "请选择" });

            foreach (TemplateModel item in dic_pro_types)
            {
                if (item.AID == selectID)
                {
                    selectTypes.Add(new SelectListItem() { Value = item.AID.ToString(), Text = item.Name, Selected = true });
                }
                else
                {
                    selectTypes.Add(new SelectListItem() { Value = item.AID.ToString(), Text = item.Name });
                }
            }
            ViewData["selTemplate"] = selectTypes;
        }

        private void InitCategoryType(string selectID)
        {
            //加载产品类型
            List<CategoryModel> dic_pro_types = db.Categorys.GetList("");
            List<SelectListItem> selectTypes = new List<SelectListItem>();

            selectTypes.Add(new SelectListItem() { Value = "00", Text = "请选择" });

            foreach (CategoryModel item in dic_pro_types)
            {
                if (item.Code == selectID)
                {
                    selectTypes.Add(new SelectListItem() { Value = item.Code.ToString(), Text = item.Name, Selected = true });
                }
                else
                {
                    selectTypes.Add(new SelectListItem() { Value = item.Code.ToString(), Text = item.Name });
                }
            }
            ViewData["selCategory"] = selectTypes;
        }

        [ValidateInput(false)]
        public ActionResult Save(ArticleModel model)
        { 
            string result = SaveStateEnum.OK.ToString();
            try
            {
                //一条新图文消息
                NewsModel nmodel = new NewsModel();
                nmodel.AID = model.NewsID;
                nmodel.CreateDate = DateTime.Now;
                nmodel.Creator = CurrentUser.UserName;
                nmodel.State = ArticleStateEnum.待发布.ToString();
                nmodel.MediaID = "";
                if (model.NewsID == 0)
                {
                    db.News.Add(nmodel);
                }
                else
                {
                    db.News.Update(nmodel);
                }

                //设置文章默认值
                model.CreateDate = DateTime.Now;
                model.Creator = CurrentUser.UserName;
                model.State = ArticleStateEnum.待发布.ToString();
                model.CategoryCode = "11"; //微信图文
                model.SubTitle = "";
                model.TemplateID = 0;
                if (db.Articles.Exists(model.NewsID)) //当前处理文章是否存在
                {
                    //存在即修改
                    db.Articles.Update(model);
                }
                else
                {
                    db.Articles.Add(model);
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "数据保存失败");
                result = SaveStateEnum.NO.ToString();
            }

            return Content(result);
        }

        public ActionResult Delete(string IDs)
        {
            string result = SaveStateEnum.NO.ToString();
            try
            {
                if (!string.IsNullOrEmpty(IDs))
                {
                    db.News.DeleteList(IDs);
                    result = SaveStateEnum.OK.ToString();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "删除数据失败!");
            }
            return Content(result);
        }

    }
}
